package com.android.jumishangcheng.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.jumishangcheng.R;
import com.android.jumishangcheng.app.BaseActivity;
import com.android.jumishangcheng.cache.DiskLruCacheHelper;
import com.android.jumishangcheng.fragment.group.Fragment_DisAndSell;
import com.android.jumishangcheng.fragment.group.Fragment_LTSecondKill;
import com.android.jumishangcheng.fragment.group.Fragment_TabBrandList;
import com.android.jumishangcheng.fragment.group.Fragment_TabNationList;
import com.android.jumishangcheng.fragment.group.Fragment_TabSearchList;
import com.android.jumishangcheng.fragment.member.Fragment_Mine_CollectGoods;
import com.android.jumishangcheng.fragment.member.Fragment_Mine_CollectStore;
import com.android.jumishangcheng.fragment.member.Fragment_Mine_Coupon;
import com.android.jumishangcheng.fragment.member.Fragment_Mine_Order;
import com.android.jumishangcheng.fragment.member.Fragment_Mine_OrderRefound;
import com.android.jumishangcheng.fragment.member.Fragment_Mine_Team;
import com.android.jumishangcheng.model.MainTabData;
import com.android.jumishangcheng.model.group.MainGoodsCatDataTwo;
import com.android.jumishangcheng.model.group.MainGoodsCatDataTwoCallback;
import com.android.jumishangcheng.model.group.MainSearchDataTotal;
import com.android.jumishangcheng.model.group.MainSearchSortData;
import com.android.jumishangcheng.model.group.SortBrandData;
import com.android.jumishangcheng.model.group.SortNationData;
import com.android.jumishangcheng.utils.ConstantsUrl;
import com.android.jumishangcheng.utils.GsonUtils;
import com.android.jumishangcheng.utils.HttpUtils;
import com.android.jumishangcheng.utils.MyLog;
import com.android.jumishangcheng.utils.ObjectUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class MainTab extends BaseActivity {
    @BindView(R.id.sort_tab)
    TabLayout sortTab;
    @BindView(R.id.sort_list)
    ImageView sortList;
    @BindView(R.id.sort_viewpager)
    ViewPager sortViewpager;
    @BindView(R.id.click_resetnetwork_msg)
    TextView clickResetnetworkMsg;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.gridView_sort)
    GridView gridView_sort;
    @BindView(R.id.pop_sort)
    LinearLayout popSort;

    private MyFragmentPagerAdapter pagerAdapter;
    private MainTab mcontext;
    private int haitaocity;
    private int tabsort_type;
    public static MainTab intance = null;
    public boolean isupdate;
    private String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maintab);
        ButterKnife.bind(this);
        mcontext = MainTab.this;
        intance = this;
        tabsort_type = getIntent().getIntExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_TYPE, 0);
        haitaocity = getIntent().getIntExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_ID, 0);
        title = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE);
        switch (tabsort_type) {
            case 0:
                initTitle(0, "品牌团");
                break;
            case 1:
                initTitle(0, "海淘团");
                break;
            case 2:
                initTitle(0, "商品列表");
                break;
            case 3:
                initTitle(0, "秒杀团");
                break;
            case 4:
                initTitle(0, "我的订单");
                break;
            case 5:
                initTitle(0, "我的团");
                break;
            case 6:
                initTitle(0, "我的收藏");
                break;
            case 7:
                initTitle(0, "我的优惠券");
                break;
            case 8:
                initTitle(0, "分销团");
                break;
            case 9:
                initTitle(0, "限时秒杀");
                break;
        }
        if(!TextUtils.isEmpty(title)){
            initTitle(0, title);
        }
        GETSortData();
    }

    public ArrayList<SortBrandData.DataBean.ListBean> mSortListdata_dapai = new ArrayList<>();
    public ArrayList<SortNationData.Nationdata> mSortListdata_nation = new ArrayList<>();
    public ArrayList<MainGoodsCatDataTwo.DataBean.Cat_ListBean> mSortListdata_search = new ArrayList<>();
    private List<MainSearchSortData.DataBean> mListSort = new ArrayList<>();
    private ArrayList<MainTabData> names = new ArrayList<>();
    private int lastPosition = 0;

    private void GETSortData() {
        try {
            DiskLruCacheHelper helper = new DiskLruCacheHelper(mcontext);
            switch (tabsort_type) {
                case 0:
                    sortTab.setTabMode(TabLayout.MODE_SCROLLABLE);
                    mSortListdata_dapai.clear();
                    String cache_dapai = helper.getAsString(ConstantsUrl.CACHE_HOME_SORTDATA_DAPAI);
                    if (!TextUtils.isEmpty(cache_dapai)) {
                        SortBrandData banner = GsonUtils.parseJSON(cache_dapai, SortBrandData.class);
                        mSortListdata_dapai.addAll(banner.getData().getList());
                        progress.setVisibility(View.GONE);
                    }
                    break;
                case 1:
                    sortTab.setTabMode(TabLayout.MODE_SCROLLABLE);
                    mSortListdata_nation.clear();
                    String cache_nation = helper.getAsString(ConstantsUrl.CACHE_HOME_SORTDATA_NATION);
                    if (!TextUtils.isEmpty(cache_nation)) {
                        SortNationData banner = GsonUtils.parseJSON(cache_nation, SortNationData.class);
                        mSortListdata_nation.addAll(banner.getData());
                        progress.setVisibility(View.GONE);
                    }
                    break;
                case 2:
                    sortTab.setTabMode(TabLayout.MODE_SCROLLABLE);
                    String id = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_TYPE_SERACH);
                    GetSortData(id);
                    progress.setVisibility(View.GONE);
                    break;
//                case 3:
//                    sortTab.setTabMode(TabLayout.MODE_FIXED);
//                    progress.setVisibility(View.GONE);
//                    names.add(new MainTabData("正在抢购", "&time=now"));
//                    names.add(new MainTabData("即将开始", "&time=well"));
//                    break;
                case 4:
                    progress.setVisibility(View.GONE);
                    sortTab.setTabMode(TabLayout.MODE_SCROLLABLE);
                    names.add(new MainTabData("全部", "0"));
                    names.add(new MainTabData("待付款", "100"));
                    names.add(new MainTabData("待发货", "101"));
                    names.add(new MainTabData("待收货", "102"));
                    names.add(new MainTabData("待评价", "110"));
                    names.add(new MainTabData("退款/售后", ""));
                    break;
                case 5:
                    progress.setVisibility(View.GONE);
                    sortTab.setTabMode(TabLayout.MODE_FIXED);
                    names.add(new MainTabData("全部", "0"));
                    names.add(new MainTabData("拼团中", "1"));
                    names.add(new MainTabData("已成团", "10"));
                    names.add(new MainTabData("拼团失败", "2"));
                    break;
                case 6:
                    progress.setVisibility(View.GONE);
                    sortTab.setTabMode(TabLayout.MODE_FIXED);
                    names.add(new MainTabData("商品", "0"));
                    names.add(new MainTabData("店铺", "1"));
                    break;
                case 7:
                    progress.setVisibility(View.GONE);
                    sortTab.setTabMode(TabLayout.MODE_FIXED);
                    names.add(new MainTabData("未使用", "1"));
                    names.add(new MainTabData("已使用/已过期", "2|3"));
                    break;
                case 8:
                    progress.setVisibility(View.GONE);
                    sortTab.setTabMode(TabLayout.MODE_FIXED);
                    names.add(new MainTabData("高佣金", "0"));
                    names.add(new MainTabData("高销量", "1"));
                    break;
                case 3:
                case 9:
                    progress.setVisibility(View.GONE);
                    sortTab.setTabMode(TabLayout.MODE_FIXED);
                    names.add(new MainTabData("正在抢购", "0"));
                    names.add(new MainTabData("即将开始", "1"));
                    break;
            }
            initUI();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initUI() {
        pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
        sortViewpager.setAdapter(pagerAdapter);
        sortTab.setupWithViewPager(sortViewpager);
        sortViewpager.setCurrentItem(haitaocity);
        sortViewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                lastPosition = position;
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @OnClick({R.id.sort_list, R.id.click_resetnetwork_refresh, R.id.close_img, R.id.close})
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.sort_list:
//                popSort.setVisibility(View.VISIBLE);
//                final GridSearchSortAdapt adapter_gridsort = new GridSearchSortAdapt(mSortListdata_search);
//                gridView_sort.setAdapter(adapter_gridsort);
//
//                gridView_sort.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                    @Override
//                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                        adapter_gridsort.setSeclection(position);
//                        adapter_gridsort.notifyDataSetChanged();
//                        sortViewpager.setCurrentItem(position);
//                        popSort.setVisibility(View.GONE);
//                    }
//                });
//                break;
            case R.id.click_resetnetwork_refresh:
                break;
            case R.id.close_img:
                popSort.setVisibility(View.GONE);
                break;
            case R.id.close:
                popSort.setVisibility(View.GONE);
                break;
        }
    }

    class MyFragmentPagerAdapter extends FragmentPagerAdapter {

        public MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (tabsort_type) {
                case 0:
                    return Fragment_TabBrandList.newInstance(mSortListdata_dapai.get(position).getId(), mSortListdata_dapai.get(position).getEnd_time());
                case 1:
                    return Fragment_TabNationList.newInstance(mSortListdata_nation.get(position).getId(), mSortListdata_nation.get(position).getThumb());
                case 2:
                    return Fragment_TabSearchList.newInstance(false, mSortListdata_search.get(position).getId(), null);
//                case 3:
//                    return Fragment_TabKillList.newInstance(names.get(position).getId());
                case 4:
                    if (position == 5) {
                        return Fragment_Mine_OrderRefound.newInstance(names.get(position).getId());
                    } else {
                        return Fragment_Mine_Order.newInstance(names.get(position).getId());
                    }
                case 5:
                    return Fragment_Mine_Team.newInstance(names.get(position).getId());
                case 6:
                    if (position == 0) {
                        return Fragment_Mine_CollectGoods.newInstance();
                    } else {
                        return Fragment_Mine_CollectStore.newInstance();
                    }
                case 7:
                    return Fragment_Mine_Coupon.newInstance(names.get(position).getId());
                case 8:
                    return Fragment_DisAndSell.newInstance(names.get(position).getId());
                case 3:
                case 9:
                    int time = getIntent().getIntExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SECONDKILL_TIME, 0);
                    String sortID = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_RATE_ID);
                    return Fragment_LTSecondKill.newInstance(time, position, sortID);
            }
            return null;
        }

        @Override
        public int getCount() {
            switch (tabsort_type) {
                case 0:
                    return mSortListdata_dapai.size();
                case 1:
                    return mSortListdata_nation.size();
                case 2:
                    return mSortListdata_search.size();
                default:
                    return names.size();
            }
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (tabsort_type) {
                case 0:
                    return mSortListdata_dapai.get(position).getCatname();
                case 1:
                    return mSortListdata_nation.get(position).getCatname();
                case 2:
                    return mSortListdata_search.get(position).getCatname();
                default:
                    return names.get(position).getName();
            }
        }
    }

    private void GetSortData(String id) {
        String address = ConstantsUrl.domain + ConstantsUrl.SORTLISTDATA_TWO;
        HashMap<String, String> map = new HashMap<>();
        map.put("id", id);
        map.put("top", id);
        MyLog.e("地址", address);
        HttpUtils.get(address, map, new MainGoodsCatDataTwoCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }

            @Override
            public void onResponse(MainGoodsCatDataTwo response, int id) {
                if (response == null) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                    return;
                }
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                if (response.getCode() == 0) {
                    mSortListdata_search.clear();
                    MainGoodsCatDataTwo.DataBean data = response.getData();
                    if (data != null && ObjectUtils.listHasData(data.getCat_list())) {
                        List<MainGoodsCatDataTwo.DataBean.Cat_ListBean> catListBeen = data.getCat_list();
                        mSortListdata_search.addAll(catListBeen);
                        initUI();
                    } else {
                        noData.setVisibility(View.VISIBLE);
                        noDataTv.setText(response.getMsg());
                        noDataTv.setVisibility(View.VISIBLE);
                    }
                } else {
                    noData.setVisibility(View.VISIBLE);
                    noDataTv.setText(response.getMsg());
                    noDataTv.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private class GridSearchSortAdapt extends BaseAdapter {

        private ArrayList<MainSearchDataTotal> listdata;

        public GridSearchSortAdapt(ArrayList<MainSearchDataTotal> listdata) {
            this.listdata = listdata;
        }

        public void setSeclection(int position) {
            lastPosition = position;
        }

        @Override
        public int getCount() {
            return listdata.size();
        }

        @Override
        public BaseObject getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = getLayoutInflater().inflate(R.layout.item_main_type_sort, null);
            TextView tv_sort = (TextView) view.findViewById(R.id.tv_sort);
            tv_sort.setText(listdata.get(position).getCatname());
            if (lastPosition == position) {
                tv_sort.setTextColor(Color.parseColor("#FF2741"));
            } else {
                tv_sort.setTextColor(Color.parseColor("#5a5a5a"));
            }
            return view;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (isupdate) {
            Intent data = new Intent();
            setResult(RESULT_OK, data);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    @OnClick(R.id.main_top_back)
    public void onClick() {
        if (isupdate) {
            Intent data = new Intent();
            setResult(RESULT_OK, data);
            finish();
        }
    }
}
